package com.czh.subject.application.Interceptor;

import com.czh.subject.common.constants.UserConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

/**
 * OpenFeign拦截器
 *<br/>这个拦截器会在使用feign调用其他服务时生效
 * <br/>用于将用户信息再次放入head
 *
 * @author caozaihui
 * @version 1.0
 * @since 2024/9/9 10:27
 */
@Slf4j
public class FeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.nonNull(servletRequestAttributes)) {
            HttpServletRequest request = servletRequestAttributes.getRequest();
            String attribute = request.getHeader(UserConstant.USER_CONTEXT_ID);
            if (Objects.nonNull(attribute)) {
                requestTemplate.header(UserConstant.USER_CONTEXT_ID, attribute);
                log.info("subject服务:feign拦截器添加了用户信息:{}", attribute);
            }else {
                log.warn("subject服务:feign拦截器没有找到用户信息");
            }

        }
    }
}
